package org.example.day20240905.dao;

import org.example.day20240905.model.User;
import org.example.day20240905.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    public boolean registerUser(User user){
        Connection connection = JDBCUtils.getConnection();
        String sql = "select count(*) as cnt from users where username = ?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1, user.getUserName());
            ps.executeQuery();
            rs = ps.getResultSet();
            while(rs.next()){
                int count = rs.getInt("cnt");
                if(count == 0){
                    String sqlInsert = "insert into users values(?,?,?,?)";
                    ps = connection.prepareStatement(sqlInsert);
                    ps.setString(1,user.getId());
                    ps.setString(2,user.getUserName());
                    ps.setString(3,user.getPassWorld());
                    ps.setString(4,user.getEmail());
                    int effectRows = ps.executeUpdate();
                    return effectRows == 1 ? true:false;
                }else {
                    return false;
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                ps.close();
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return true;
    }


}
